package com.fc.remoting.handler;

import java.util.concurrent.RejectedExecutionException;

import com.alibaba.fastjson.JSONObject;
import com.fc.remoting.RemotingConst;
import com.fc.remoting.exception.IRemotingException;
import com.fc.remoting.logger.LogSystem;
import com.fc.remoting.logger.MonitorConfig;
import com.fc.remoting.logger.Monitorlogger;
import com.fc.remoting.logger.RemotingLogger;
import com.fc.remoting.message.Commond;
import com.fc.remoting.message.DefaultRemotingMessage;
import com.fc.remoting.message.RemotingMessage;
import com.fc.remoting.message.RemotingMessageType;
import com.fc.remoting.protocol.ProtocolAdapter;
import com.fc.remoting.protocol.ProtocolRegister;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class RemotingServerMessageHandler extends SimpleChannelInboundHandler<RemotingMessage> {
	
	private static final String DEFAULT_ENCODE = "UTF-8";
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		ctx.close();
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, RemotingMessage msg) throws Exception {
		
	
		Channel channel = ctx.channel();
		if (msg == null) {
			return;
		}
		try {
			int msgType = msg.getHeader().getMsgType();
			if (msgType == RemotingMessageType.HEART_BEAT) {
				ctx.channel().writeAndFlush(DefaultRemotingMessage.heartBeatMessage());
				return;
			}
			
			JSONObject requestBody = JSONObject.parseObject(new String(msg.getBody(),DEFAULT_ENCODE));
			int module= requestBody.getIntValue(RemotingConst.MODULE);
			int order = requestBody.getIntValue(RemotingConst.ORDER);
			Commond commond = Commond.valueOf(module, order);
			ProtocolAdapter processor = ProtocolRegister.getAdapter(commond);
			if (processor == null) {
//				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.handleModule, MonitorConfig.fail,null,requestBody,null,"commond[" + commond.toString() + "] is not exist");
				throw new NullPointerException("commond[" + commond.toString() + "] is not exist");
			}
			processor.processTcpRequest(requestBody, channel);
		} catch (RejectedExecutionException e) {
			RemotingLogger.getLogger().error(e.getMessage(), msg);
			throw new IRemotingException(e.getMessage(), e);
		} catch (Exception e) {
			RemotingLogger.getLogger().error(e.getMessage(), msg);
			throw new IRemotingException(e.getMessage(), e);
		}
	}
}
